package com.jzit.network.utils

import android.accounts.NetworkErrorException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

/*
    ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
       Author   :  zhouxc
       Date     :  2022/10/26
       Time     :  14:40
    ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
 */
object DownLoadFileUtils {
    fun downloadFile(url: String, file: File): Flow<DownLoadStatus> {
        return flow {
            val request = Request.Builder().url(url).build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if (response.isSuccessful) {
                response.body()!!.let { body ->
                    val total = body.contentLength()
                    file.outputStream().use {
                        val input = body.byteStream()
                        var progress = 0L
                        val currentProgress = input.copyTo(it)
                        var progressC = currentProgress * 100 / total
                        if (progressC - progress > 5) {
                            delay(100)
                            emit(DownLoadStatus.Progress(progressC.toInt()))
                            progress = progressC
                        }
                    }
                }
                emit(DownLoadStatus.DownloadComplete(file))
            } else {
                throw NetworkErrorException(response.toString())
            }
        }.catch {
            file.delete()
            emit(DownLoadStatus.Error(it))
        }.flowOn(Dispatchers.IO)
    }
}